﻿using System;
using System.Windows.Forms;
using Groove.Core.Cache;
using Groove.Core.Infrastructure;
using Groove.Core.MediaFile;
using Groove.Core.Player;
using Groove.Core.Win32;
using SchwabenCode.QuickIO;

namespace Groove.Winform
{
    public partial class MainForm : Form
    {
        //private List<IMediaFile> _playList = new List<IMediaFile>();
        private string _musicFolder;
        private string CacheFilePath => AppDomain.CurrentDomain.BaseDirectory + "cache.json";

        public MainForm()
        {
            InitializeComponent();
            ResovleTitleDrag();
            RegisterControlButtonEvents();
            RegisterPlayerEvents();
            Shown += MainForm_Shown;
            FormClosed += MainForm_FormClosed;
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            ucPlayer.InitPlayer();
            LoadCache();
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            SaveCache();
        }

        private void ResovleTitleDrag()
        {
            pnlTitle.MouseDown += Title_MouseDown;
            lblTitle.MouseDown += Title_MouseDown;
        }

        private void Title_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Left) return;
            User32.ReleaseCapture();
            User32.SendMessage(Handle, 0x00A1, 2, 0);
        }

        private void RegisterControlButtonEvents()
        {
            btnClose.Click += (s, args) =>
            {
                Close();
            };
            btnMinimum.Click += (s, args) =>
            {
                WindowState = FormWindowState.Minimized;
            };
            btnPcMusic.ControlClicked += BtnPcMusic_ControlClicked;
        }

        private void BtnPcMusic_ControlClicked(object sender, EventArgs e)
        {
            var folderBrowerDlg = new FolderBrowserDialog();
            folderBrowerDlg.Description = @"请选择本地音乐目录";
            if (folderBrowerDlg.ShowDialog() != DialogResult.OK) return;
            UpdateMusicFolder(folderBrowerDlg.SelectedPath, ucPlayer.CurrentMediaFile?.FullFileName);
        }

        private IMediaFile UpdateMusicFolder(string folder,string playingFile)
        {
            if (string.IsNullOrEmpty(folder)) return null;
            _musicFolder = folder;
            var  playList = LocalMediaFileFinder.SearchMediaFiles(folder);
            ucPlaylist.SetPlaylist(playList);

            if (string.IsNullOrEmpty(playingFile)) return null;
            var playingMediaFile = ucPlaylist.Playlist.Find(o => o.FullFileName == playingFile);
            if (playingMediaFile == null) return null;
            ucPlaylist.SetPlayingFile(playingMediaFile);
            return playingMediaFile;
        }

        private void RegisterPlayerEvents()
        {
            ucPlaylist.MediaFileSelected += (s, e) =>
            {
                var selectedMediaFile = ucPlaylist.SelectedMediaFile;                
                SetPlayingMediaFile(selectedMediaFile,true);                
            };
            ucPlayer.Next += UcPlayer_Next;
            ucPlayer.Previous += UcPlayer_Previous;
        }

        private void UcPlayer_Previous(object sender, EventArgs e)
        {
            ucPlaylist.SelectIndex(ucPlaylist.PreviousIndex);
        }

        private void UcPlayer_Next(object sender, EventArgs e)
        {
            this.DoInvoke(() =>
            {
                switch (ucPlayer.PlayMode)
                {
                    case PlayMode.ListCycle:
                    case PlayMode.SingleCycle:
                        var index = ucPlaylist.CurrentIndex + 1;
                        if (index >= ucPlaylist.PlaylistLength)
                            index = 0;
                        ucPlaylist.SelectIndex(index);
                        break;
                    case PlayMode.RandomPlay:
                        var r = new Random(Environment.TickCount);
                        var rIndex = r.Next(0, ucPlaylist.PlaylistLength - 1);
                        ucPlaylist.SelectIndex(rIndex);
                        break;
                }
            });            
        }

        private void LoadCache()
        {
            if (!QuickIOFile.Exists(CacheFilePath)) return;
            var jsonStr = QuickIOFile.ReadAllText(CacheFilePath);
            if (string.IsNullOrEmpty(jsonStr)) return;
            var playerCache = jsonStr.DeserializeJsonObject<PlayerCache>();
            if (playerCache == null || playerCache.IsEmpty)
            {
                return;
            }
            var playingFile = UpdateMusicFolder(playerCache.MusicFolder, playerCache.PlayingMediaFileFullPath);
            if (playingFile != null)
                SetPlayingMediaFile(playingFile, false);
        }

        private void SaveCache()
        {
            var playerCache = new PlayerCache()
            {
                MusicFolder = _musicFolder,
                PlayingMediaFileFullPath = ucPlayer.CurrentMediaFile?.FullFileName
            };
            var jsonStr = playerCache .ToJsonString();
            if (QuickIOFile.Exists(CacheFilePath)) QuickIOFile.Delete(CacheFilePath);
            QuickIOFile.WriteAllText(CacheFilePath, jsonStr);
        }

        private void SetPlayingMediaFile(IMediaFile playingMediaFile, bool startToPlay)
        {
            picAlnum.Image = playingMediaFile.AlbumCover ?? Properties.Resources.Tape;
            ucPlayer.SetCurrentMediaFile(playingMediaFile, startToPlay);
        }
    }
}
